package com.qtenv.datasync.worker.huizhong;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qtenv.datasync.api.huizhong.GetMethodsServiceLocator;
import com.qtenv.datasync.base.ArchiveSyncer;
import com.qtenv.datasync.constant.AppConstants;
import com.qtenv.datasync.service.entity.Terminals_bf;
import com.qtenv.datasync.service.entity.huizhong.HZTerminals;
import org.springframework.stereotype.Component;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.List;

/**
 * @ClassName HZArchiveSyncWorker
 * @Author CBL
 * @Date 2022/2/23 15:48
 **/
@Component
public class HZArchiveSyncWorker extends ArchiveSyncer {

    public HZArchiveSyncWorker() {
        super("汇中");
    }

    @Override
    public List<Terminals_bf> getTerminals() {
        List<Terminals_bf> terminals = null;
        GetMethodsServiceLocator hzService = new GetMethodsServiceLocator();
        try {
            String terminalData = hzService.getGetMethods().getUserData(AppConstants.HZ_ZC_TENANT_ID);
            if (StrUtil.isNotEmpty(terminalData)) {
                terminals = this.transform(terminalData);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }

        System.out.println("从厂家【" + this.getSupplier() + "】获取【档案】数量：" + terminals.size());
        return terminals;
    }

    private List<Terminals_bf> transform(String terminalData) {
        List<Terminals_bf> result = CollectionUtil.newArrayList();

        JSONObject jsonObject = JSON.parseObject(terminalData);
        List<HZTerminals> hzTerminalList = JSON.parseArray(jsonObject.getString(AppConstants.HZ_DATA_KEY), HZTerminals.class);
        hzTerminalList.forEach(hzTerminals -> {
            Terminals_bf terminals = new Terminals_bf();
            BeanUtil.copyProperties(hzTerminals, terminals, "Caliber");
            terminals.setTenant_id(AppConstants.APP_TENANT_ID);
            terminals.setSupplierID(AppConstants.HZ_SUPPLIER_ID);
            terminals.setTerminalMark(1);
            terminals.setUserArea(AppConstants.APP_TENANT_ID);
            String caliber = hzTerminals.getCaliber();
            if (StrUtil.isNotEmpty(caliber)) {
                caliber = StrUtil.replaceIgnoreCase(caliber, "DN", "");
                terminals.setCaliber(Integer.valueOf(caliber));
            }
            result.add(terminals);
        });

        return result;
    }

    public static void main(String[] args) {
        HZArchiveSyncWorker worker = new HZArchiveSyncWorker();
//        System.out.println(JSON.toJSONString(worker.getTerminals(), true));
        worker.syncTerminals();
    }
}
